package com.topdt.jbpm.web.struts.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.web.ActionResult;
import com.thx.file.service.FileManager;
import com.thx.log.LogUtil;
import com.topdt.jbpm.model.Signature;
import com.topdt.jbpm.service.SignatureService;
import com.topdt.jbpm.utils.ModuleConstant;

/**  
 *  @Project       : thx-workflow
 *  @Program Name  : com.topdt.jbpm.web.struts.action.SignatureAction.java
 *  @Class Name    : SignatureAction
 *  @Description   : 公文管理/签章
 *  @Author        : calonlan
 *  @Creation Date : 2015年4月13日 上午11:05:26 
 *  @ModificationHistory  
 *  Who        When          What 
 *  --------   ----------    -----------------------------------
 *  username   2015年4月13日       TODO
 */
@Namespace("/workflow")
@Action(value = "signature", results = {
		@Result(name = "list", location = "/workflow/signature/list.jsp"),
		@Result(name = "view", location = "/workflow/signature/detail.jsp"),
		@Result(name = "input", location = "/workflow/signature/input.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" })
})
@Controller
@Scope("prototype")
public class SignatureAction extends CurdAction<Signature> {
	
	private static final long serialVersionUID = 622423569825277997L;
	
	@Autowired
	private SignatureService signatureService;
	
	@Autowired
	private FileManager fileManager;
	
	private java.io.File image;
	
	private String imageFileName;
	
	private String imageContentType;

	@Override
	protected void doList() throws Exception {
		logger.debug("<进入>:doList方法");
		list = signatureService.findByName(entity.getName());
	}

	@Override
	protected void doInput() throws Exception {
		logger.debug("<进入>:doInput方法");
		if (StringUtils.isNotBlank(id)) {
			entity = signatureService.get(Integer.parseInt(id));
			if (entity == null) {
				setResult(ActionResult.FAIL, "要修改的记录不存在！");
			}
		}
	}

	@Override
	protected void doView() throws Exception {
		logger.debug("<进入>:doView方法");
		if (StringUtils.isNotBlank(id)) {
			entity = signatureService.get(Integer.parseInt(id));
			if (entity == null) {
				setResult(ActionResult.FAIL, "要查看的记录不存在！");
			}
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}

	@Override
	protected void doSave() throws Exception {
		logger.debug("<进入>:doSave方法    新增或修改签章");
		if (StringUtils.isBlank(id)) {
			//设置文件相关
			if (image != null) {
				InputStream is = new FileInputStream(image);
				byte[] buff = new byte[(int) image.length()];
				int count = 0;
				int temp = 0;
				while ((temp = is.read()) != (-1)) {
					buff[count++] = (byte) temp;
				}
				is.close();
				entity.setBody(buff);
				entity.setSize((int)image.length());
				entity.setType(imageFileName.substring(imageFileName.lastIndexOf(".")));
			}
			
			entity.setCompanyId(AppContext.getCurrentComId());
			signatureService.save(entity);
			setResult(ActionResult.SUCCESS, "添加成功！");
			LogUtil.log(ModuleConstant.SIGNATURE, LogUtil.ACTION_ADD, ActionResult.SUCCESS, "新增签章");
		} else {
			Signature signature = signatureService.get(Integer.parseInt(id));
			//设置文件相关
			if (image != null) {
				InputStream is = new FileInputStream(image);
				byte[] buff = new byte[(int) image.length()];
				int count = 0;
				int temp = 0;
				while ((temp = is.read()) != (-1)) {
					buff[count++] = (byte) temp;
				}
				is.close();
				signature.setBody(buff);
				signature.setSize((int)image.length());
				signature.setType(imageFileName.substring(imageFileName.lastIndexOf(".")));
			}
			/*//test
			String path = ServletActionContext.getServletContext().getRealPath("/")+java.io.File.separator + "upload/2015/04/13/2015041316592259576.jpg";
			File file = new File(path);
			InputStream is = new FileInputStream(file);
			//response.setContentType("image/jpeg");
			//InputStream is = new ByteArrayInputStream(buff);
			int temp =0;
			int count = 0;
			byte[] buf = new byte[(int) file.length()];
			try {
				//OutputStream os = response.getOutputStream();
				while((temp = is.read()) != -1) {
					buf[count++] = (byte) temp;
					//os.write(temp);
				}
				//os.write(buff);
				//os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			signature.setBody(buf);*/
			//test end
			signature.setName(entity.getName());
			signature.setUsername(entity.getUsername());
			signature.setPassword(entity.getPassword());
			
			signatureService.update(signature);
			setResult(ActionResult.SUCCESS, "修改成功！");
			LogUtil.log(ModuleConstant.SIGNATURE, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改签章");
		}
	}

	@Override
	protected void doDelete() throws Exception {
		logger.debug("<进入>:doDelete方法    删除签章");
		if (StringUtils.isNotBlank(id)) {
			signatureService.delete(Integer.parseInt(id));
			setResult(ActionResult.SUCCESS, "删除成功！");
			LogUtil.log(ModuleConstant.SIGNATURE, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除签章");
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}

	@Override
	protected void doDelMulti() throws Exception {
		logger.debug("<进入>:doDelMulti方法    删除签章");
		if (delId != null && delId.length > 0) {
			delId = delId[0].split(",");
			for (String id : delId) {
				signatureService.delete(Integer.parseInt(id));
			}
			setResult(ActionResult.SUCCESS, "删除成功！");
			LogUtil.log(ModuleConstant.SIGNATURE, LogUtil.ACTION_DELETE, ActionResult.SUCCESS, "删除签章");
		} else {
			setResult(ActionResult.FAIL, "服务器异常");
		}
	}
	
	public void checkSignatureName() {
		logger.debug("<进入>:checkSignatureName方法");
		List<Signature> list = signatureService.findByNameNoPage(entity.getName());
		try {
			if (list == null || list.size() <= 0) {
				writeJson("true");
			} else {
				if (list.get(0).getSignatureId().equals(Integer.parseInt(id))) {
					writeJson("true");
				} else {
					writeJson("false");
				}
			}
		} catch (IOException e) {
			logger.error("<错误>:"+e.getMessage());
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}
	
	public void showPicture() throws IOException {
		logger.debug("<进入>:showPicture方法");
		Signature signature = signatureService.get(Integer.parseInt(id));
		HttpServletResponse response = ServletActionContext.getResponse();
		response.reset(); // 非常重要
		response.setCharacterEncoding("utf-8");
		String type = signature.getType();
		type = type.substring(1);
		byte[] buff = signature.getBody();
		response.setContentType("image/"+type);
		OutputStream os = response.getOutputStream();
		os.write(buff);
		os.flush();
	}

	public java.io.File getImage() {
		return image;
	}

	public void setImage(java.io.File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}
	
}
